// Modules to control application life and create native browser window
const {app, BrowserWindow,ipcMain,session,NativeImage } = require('electron')
const Store = require('electron-store');
// 引入node的 path 和url模块
const path = require('path')
const url = require('url');
const netease = require('./request/netease');
const qq = require('./request/qq');
const migu = require('./request/migu');
const kugou = require('./request/kugou');
const kuwo = require('./request/kuwo');
const Menu = require('./menu');

// 获取在 package.json 中的命令脚本传入的参数，来判断是开发还是生产环境
const mode = process.argv[2];

function createWindow () {
    // Create the browser window.
    let mainWindow = new BrowserWindow({
        width: 1600, // 窗口宽度
        height: 1000, // 窗口高度
        title: "Music-X", // 窗口标题,如果由loadURL()加载的HTML文件中含有标签<title>，该属性可忽略
        icon: 'build/logo512.ico', // "string" || nativeImage.createFromPath('src/image/icons/256x256.ico')从位于 path 的文件创建新的 NativeImage 实例
        webPreferences: { // 网页功能设置
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true, // 是否启用node集成 渲染进程的内容有访问node的能力
            webviewTag: true, // 是否使用<webview>标签 在一个独立的 frame 和进程里显示外部 web 内容
            webSecurity: false, // 禁用同源策略
            nodeIntegrationInSubFrames: true, // 是否允许在子页面(iframe)或子窗口(child window)中集成Node.js
            contextIsolation: false,
            devTools:true,
            partition:'main',
        },
        frame:false
    })


    // and load the index.html of the app.
    //判断是否是开发模式
    if(mode === 'dev') {
        mainWindow.loadURL("http://localhost:3000/")
    } else {
    mainWindow.loadURL(url.format({
        pathname:path.join(__dirname, './www/index.html'),
        // pathname:path.join(__dirname, './public/Test.html'),
        protocol:'file:',
        slashes:true
    }))
        // mainWindow.loadFile('./build/index.html')
    }

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
    // mainWindow.setMenu(null)  //关闭菜单
    let init163 = new netease();
    let initqq = new qq();
    let initmigu = new migu();
    let initkugou = new kugou();
    let initkuwo = new kuwo();
    init163.init();
    initqq.init();
    initmigu.init();
    initkugou.init();
    initkuwo.init();
    new Menu(mainWindow);

    //登录qq的监听
    ipcMain.on('loginQQwindow',(e,args) => {
        const child = new BrowserWindow({
            parent: mainWindow, modal: true,
            show: false,
            width:1200,
            webPreferences:{
                partition:'qq'
            }
        })
        child.loadURL('https://y.qq.com/')
        child.once('ready-to-show', () => {
            child.show()
        })
        let cookiesChild = child.webContents.session.cookies;
        session.defaultSession.cookies.get({ domain: '.qq.com' })
            .then((cookies) => {
                let flag = false;
                cookies.map((r) => {
                 if(r.name === 'uin'){
                     flag = true;
                 }
                })
                if(flag) {
                    let result = "";
                    for (const c of cookies) {
                        result += c.name + '=' + c.value + ';'
                    }
                    mainWindow.webContents.send('getQQcookies', result);
                    child.close();
                }
            }).catch((error) => {
            //console.log(error)
        })
        ipcMain.on('cleanQQcookie',(e,args) => {
           //console.log('clean')
            cookiesChild.get({ domain: '.qq.com' })
                .then((cookies) => {
                   //console.log(cookies)
                    cookies.forEach(cookie => {
                        let url = '';
                        // get prefix, like https://www.
                        url += cookie.secure ? 'https://' : 'http://';
                        url += cookie.domain.charAt(0) === '.' ? 'www' : '';
                        // append domain and path
                        url += cookie.domain;
                        url += cookie.path;
                       //console.log('1'+url,cookie.name)
                        cookiesChild.remove(url, cookie.name, (error) => {
                            if (error) console.log(`error removing cookie ${cookie.name}`, error);
                        });
                    })
                }).catch((error) => {
               //console.log(error)
            })
            cookiesChild.get({ domain: '.y.qq.com' })
                .then((cookies) => {
                    cookies.forEach(cookie => {
                        let url = '';
                        // get prefix, like https://www.
                        url += cookie.secure ? 'https://' : 'http://';
                        url += cookie.domain.charAt(0) === '.' ? 'www' : '';
                        // append domain and path
                        url += cookie.domain;
                        url += cookie.path;
                       //console.log('2'+url,cookie.name)

                        cookiesChild.remove(url, cookie.name, (error) => {
                            if (error) console.log(`error removing cookie ${cookie.name}`, error);
                        });
                    })
                }).catch((error) => {
                console.log(error)
            })
        })

        cookiesChild.on('changed', (e, cookie, cause, removed) => {

            let uin = cookie.name;
            if(uin === 'uin' ){
               //console.log("``````````````123````````````````````")
               //console.log(cause)
               //console.log(cookie.value)
                setTimeout(() => {
                    let result = "";
                    cookiesChild.get({ domain: '.qq.com' })
                        .then((cookies) => {
                            for (const c of cookies) {
                                result += c.name+'='+c.value+';'
                            }

                           //console.log(result)
                            try {
                                child.close();
                                mainWindow.webContents.send('getQQcookies',result);
                            }catch (e){
                                console.log('已关闭',e)
                            }

                        }).catch((error) => {
                        console.log(error)
                    })

                },2000)
            }
        });

    })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.

app.whenReady().then(() => {
    // require('./doBeforeHttp');
    createWindow()

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
